use actix_web::{HttpRequest, delete, get, post, web};

use log::{info, trace};
use rbase::{
    define::{ApiError, ApiResponse},
    id_utils::{opt_id2str, opt_str2id},
};
use rbase_iam::rest_api::service::auth_check::get_user_from_request;
use serde::{Deserialize, Serialize};

use crate::{
    db::entities::knowledge_progress::Model,
    rest_api::service::srv_knowledge_progress::{self},
};

use anyhow::Result;
use rbase::id_utils::{id2str, str2id};

#[derive(Clone, Debug, Deserialize)]
pub struct CreateParams {
    pub scheduler_id: String,
    pub knowledge_ids: Vec<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct KnowledgeProgress {
    pub id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduler_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub knowledge_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub learned_count: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub learning_point: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<i64>,
}

impl KnowledgeProgress {
    pub fn from_model(entity: &Model) -> Self {
        KnowledgeProgress {
            id: id2str(entity.id),
            name: None,
            created_at: entity.created_at,
            modified_at: entity.modified_at,
            scheduler_id: opt_id2str(&entity.scheduler_id),
            knowledge_id: opt_id2str(&entity.knowledge_id),
            learned_count: entity.learned_count,
            learning_point: entity.learning_point,
        }
    }

    pub fn to_model(&self) -> Result<Model> {
        Ok(Model {
            id: str2id(&self.id)?,
            created_at: self.created_at,
            modified_at: self.modified_at,
            scheduler_id: opt_str2id(&self.scheduler_id)?,
            knowledge_id: opt_str2id(&self.knowledge_id)?,
            learned_count: self.learned_count,
            learning_point: self.learning_point,
            owner_id: None,
        })
    }
}

#[derive(Deserialize, Debug)]
pub struct SearchParams {
    #[serde(default)]
    pub scheduler_id: Option<String>,

    #[serde(default)]
    pub subject_id: Option<String>,

    #[serde(default)]
    pub category_id: Option<String>,

    #[serde(default)]
    pub tag_ids: Option<Vec<String>>,

    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub offset: Option<u64>,

    #[serde(default)]
    pub limit: Option<u64>,

    #[serde(default)]
    pub order_by: Option<String>,

    #[serde(default)]
    pub order: Option<String>,

    #[serde(default)]
    pub cols: Option<Vec<String>>,
}

#[get("/api/v1/knowledge_progresses")]
async fn list_knowledge_progresses(req: HttpRequest, query_params: web::Query<SearchParams>) -> Result<ApiResponse, ApiError> {
    let knowledge_search_params = query_params.into_inner();
    trace!("list_knowledge_progresses   query: {:?}", knowledge_search_params);
    let user_token = get_user_from_request(&req)?;
    let (knowledge, total) = srv_knowledge_progress::search(&user_token, &knowledge_search_params).await?;
    Ok(ApiResponse::datas(knowledge, total))
}

#[post("/api/v1/knowledge_progresses")]
async fn create_knowledge_progress(req: HttpRequest, req_body: String) -> Result<ApiResponse, ApiError> {
    trace!("create_knowledge_progress body: {}", req_body);
    let user_token = get_user_from_request(&req)?;
    let new_knowledge_progresse: CreateParams = serde_json::from_str(&req_body)?;

    let knowledge_progress = srv_knowledge_progress::create_knowledge_progress(&user_token, &new_knowledge_progresse).await?;
    Ok(ApiResponse::data(knowledge_progress))
}

#[get("/api/v1/knowledge_progresses/{id}")]
async fn get_knowledge_progress(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    let knowledge_progresse_id = path_params.into_inner();
    trace!("get_knowledge_progress path: {:?}", knowledge_progresse_id);
    let user_token = get_user_from_request(&req)?;
    let result = srv_knowledge_progress::find_knowledge_proogress_by_id(&user_token, &knowledge_progresse_id).await?;
    Ok(ApiResponse::data(result))
}

#[delete("/api/v1/knowledge_progresses/{id}")]
async fn delete_knowledge_progress(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("delete_knowledge_progress path: {:?}", path_params);
    let user_token = get_user_from_request(&req)?;
    let knowledge_progresse_id = path_params.into_inner();
    let result = srv_knowledge_progress::delete_knowledge_progress_by_id(&user_token, &knowledge_progresse_id).await?;
    Ok(ApiResponse::data(result))
}

pub fn config(cfg: &mut web::ServiceConfig) {
    info!("Configuring knowledge APIs");
    cfg.service(list_knowledge_progresses);
    cfg.service(create_knowledge_progress);
    cfg.service(get_knowledge_progress);
    cfg.service(delete_knowledge_progress);
}
